package com.cdfahe.common.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.springframework.web.multipart.MultipartFile;

import com.cdfahe.common.Constants;

/**
 * 操作文件工具类
 * @author Administrator
 *
 */
public class FileUtils {
	/**
	 * 保存药品图片的方法
	 * @param file
	 * @param saveDir
	 * @param rootdir
	 * @return
	 */
	public static String saveFile(MultipartFile file,String saveDir, String rootdir){
		   if(!file.isEmpty()){
				 long fileSize = file.getSize();
				 String fileName = file.getOriginalFilename();
				 String contentType=file.getContentType();
				 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();//文件后缀
				 if(fileSize > Constants.MAX_UPDATE_FILE){
					 //writer.println(getError("上传文件大小超过限制10M。"));
					 
				 }
				 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				 String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
				 
				try{
					 File root = new File(rootdir + saveDir);
					 if (!root.exists()) {
						 root.mkdirs();
					}
					  File uploadedFile = new File(rootdir + saveDir, newFileName);
					  file.transferTo(uploadedFile);  
				 }catch(Exception e){
				 }
				return "/cdfahe/" + saveDir+"/" + newFileName;
				
	        } else {
	        	return null;
	        }
	}
}
